import Vue from "vue";
import axios from "axios";
import localStore from "../store"
import Message from "element-ui/packages/message/src/main";

Vue.prototype.$http = axios
/*
  axios全局默认设置
 */
axios.defaults.timeout = 5000
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// axios.defaults.withCredentials = false
/*
  axios实例
 */
const instance = axios.create({
  baseURL: 'http://localhost:9001'
})
instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

/*
  request拦截器
 */
instance.interceptors.request.use(
  config => {
    //每次发送请求之前检查Vuex中是否存在token,如果存在则放在请求头中发给服务器
    if(localStore.state.userToken){
      config.headers['userToken'] = `token ${localStore.state.userToken}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

/*
  response拦截器
 */
instance.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default instance
